/*
 * FilePath     : \src\utils\logger.ts
 * Author       : 苏军志
 * Date         : 2023-09-01 16:08
 * LastEditors  : 苏军志
 * LastEditTime : 2023-11-08 18:12
 * Description  : 日志工具类
 * CodeIterationRecord:
 */

interface log {
  title: string;
  content?: string;
  api?: string;
}

/**
 * 设置日志
 * data: 日志参数
 */
const setLogger = async (data: log) => {
  let logger = common.session("logger");
  if (!logger) {
    logger = { loggerList: [], loggerSteps: 0 };
  }
  logger.loggerSteps++;
  logger.loggerList.push({
    ...data,
    page: window.location.href,
    steps: logger.loggerSteps,
    time: new Date()
  });
  try {
    await common.session("logger", logger);
  } catch (e: any) {
    // session存储空间满了，就把现有日志提交服务器
    if (e.name === "QuotaExceededError") {
      await commitServer();
      await common.session("logger", logger);
    }
  }
};

/**
 * 保存日志到服务器
 * data: 日志参数
 */
const commitServer = async () => {
  let logger = common.session("logger");
  if (logger?.loggerList?.length) {
    await operationLogService.saveLog(logger.loggerList);
    logger.loggerList = [];
    common.session("logger", logger);
  }
};
export default {
  setLogger,
  commitServer
};
